//
//  HouseCleanViewController.m
//  Housekeeping
//
//  Created by 辰领科技 on 16/5/18.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "HouseCleanViewController.h"
#import "YMDDateAlertView.h"
#import "SureIndentViewController.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "HouseCleanDetailViewController.h"
#import "GoodsCommentViewController.h"
#import "GoodsComentTableViewCell.h"
static NSString *cellIdentify = @"GoodsComentTableViewCell";
@interface HouseCleanViewController ()<BestScrollViewDelegate,BestScrollViewDatasource,UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIButton *moreButton;
@property (weak, nonatomic) IBOutlet UITextField *houseSizeLabel;
@property (weak, nonatomic) IBOutlet UITextField *dateTimeLabel;
@property (weak, nonatomic) IBOutlet UITextField *phoneLabel;
@property (strong, nonatomic) IBOutlet UIView *shareView;
@property (strong, nonatomic) IBOutlet UIButton *closeShareButton;

//商品信息
@property(nonatomic,strong)NSDictionary * productDic;
@property (weak, nonatomic) IBOutlet UILabel *goodsName;
@property (weak, nonatomic) IBOutlet UILabel *goodsDetail;
@property (weak, nonatomic) IBOutlet UILabel *totalSize;
@property (weak, nonatomic) IBOutlet UILabel *specifyLabel;//规格
@property(nonatomic,strong)NSString * specify;//单位
@property (weak, nonatomic) IBOutlet UIButton *commentCount;
@property (weak, nonatomic) IBOutlet UIButton *collectButton;
@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property (nonatomic,strong)  NSMutableArray  *imageArray;

@property(nonatomic,strong)NSMutableArray * commitArray;
@property(nonatomic,strong)NSMutableArray * heightArray;
@end

@implementation HouseCleanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _imageArray = [NSMutableArray array];
    _heightArray = [NSMutableArray array];
    [self initViewLayout];
    [self getGoodsDetail];
    [self getCommentsList];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.shareView];
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 750), NO);
    _houseSizeLabel.layer.borderWidth = 1;
    _houseSizeLabel.layer.borderColor = [UIColor colorWithWhite:0.855 alpha:1.000].CGColor;
    _houseSizeLabel.delegate = self;
    
    //广告栏
    _headerScroll=[[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 170), NO)];
    [self.scroView insertSubview:_headerScroll atIndex:0];
    
    _moreButton.layer.cornerRadius = 16.5*VerticalRatio();
    UIImage * image = [UIImage imageNamed:@"houseClean9"];
    CGSize  size = [_moreButton.titleLabel.text sizeWithFont:_moreButton.titleLabel.font];
    [_moreButton setTitleEdgeInsets:UIEdgeInsetsMake(0, -image.size.width*VerticalRatio(), 0, image.size.width*VerticalRatio())];
    [_moreButton setImageEdgeInsets:UIEdgeInsetsMake(0, size.width, 0, - size.width)];
    
    [self.tableView registerNib:[UINib nibWithNibName:cellIdentify bundle:nil] forCellReuseIdentifier:cellIdentify];
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark === 商品详情
- (void)getGoodsDetail{

    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"sectionId"] forKey:@"mstoAreaId"];
    [dic setObject:_goodsId forKey:@"goodsId"];
    if ([Common getLoginStatus]){
         [dic setObject:[Common getLoginInfo][Key_User_userId] forKey:@"museId"];
    }
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryMallGoods withHttpType:@"POST" withTag:HK_HK_queryMallGoods];
    
}

#pragma mark === 获取评论列表
- (void)getCommentsList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[NSNumber numberWithInt:1] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInt:PageSize] forKey:@"pageSize"];
    [dic setObject:_goodsId forKey:@"goodsId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:HK_queryAppMallGoodsComment withHttpType:@"POST" withTag:HK_HK_queryAppMallGoodsComment];
    
}

#pragma mark === 设置预约时间
- (IBAction)dateTimeHandel:(id)sender {
    YMDDateAlertView * dateView = [[YMDDateAlertView alloc]initWithTitle:@"设置预约时间" sureButtonTitle:@"确定" limitDate:YES dateType:2 complect:^(NSString *str) {
        _dateTimeLabel.text = str;
    }];
    [dateView show];
}

#pragma mark === 收藏
- (IBAction)collectHandel:(UIButton*)sender {
    
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate] ShowLoginPage];
        return;
    }
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[[Common getLoginInfo] objectForKey:Key_User_password] forKey:@"musePwd"];
    [dic setObject:[[Common getLoginInfo] objectForKey:Key_User_onlineKey] forKey:@"museOnlineTag"];
    if (sender.selected) {
        [dic setObject:_goodsId forKey:@"mgooId"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:HK_deleteCollectGoods withHttpType:@"POST" withTag:HK_HK_deleteCollectGoods];
    }else{
        [dic setObject:_productDic[@"mgooPrice"] forKey:@"mcgoMcgoPrice"];
        [dic setObject:_goodsId forKey:@"mcgoGoodsId"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:HK_collectGoods withHttpType:@"POST" withTag:HK_HK_collectGoods];
    }
    

}

#pragma mark == 分享
- (IBAction)shareHandel:(id)sender {

        _shareView.hidden = NO;
        _closeShareButton.hidden = NO;
   
}

- (IBAction)shareToWechatSession:(UIButton *)sender {
    
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:_goodsName.text image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            //            NSLog(@"分享成功！");
        }
    }];
}
- (IBAction)shareToWechatTimeline:(UIButton *)sender {
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:_goodsName.text image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            //            NSLog(@"分享成功！");
        }
    }];
}
- (IBAction)shareToQzone:(UIButton *)sender {
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQzone] content:_goodsName.text image:[UIImage imageNamed:@"58.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            //            NSLog(@"分享成功！");
        }
    }];
}
- (IBAction)shareToQQ:(UIButton *)sender {
    [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ] content:_goodsName.text image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            //            NSLog(@"分享成功！");
        }
    }];
}


- (IBAction)closeShareView:(id)sender {
    _closeShareButton.hidden = YES;
    _shareView.hidden = YES;
}

#pragma mark  ===== 电话
- (IBAction)callHandel:(id)sender {
    [Common callPhone:_phoneLabel.text view:self.view];
}
#pragma mark == 立即预约
- (IBAction)buyNow:(id)sender {
    
    if ([Common dataIsNULL:_houseSizeLabel.text]) {
        [CWHUDTips showTips:@"请输入房间大小"];
        return;
    }
    if ([Common dataIsNULL:_dateTimeLabel.text]) {
        [CWHUDTips showTips:_dateTimeLabel.placeholder];
        return;
    }
    
    //判断最低价
    CGFloat lowPrice = [_productDic[@"mgooSalePrice"]floatValue];
    CGFloat price = [_productDic[@"mgooPrice"]floatValue];
    CGFloat countPrice = price*[_houseSizeLabel.text integerValue];
    NSString * notice = [NSString stringWithFormat:@"亲,最低消费金额为%.0f元,确认订单?",lowPrice];
    if (countPrice<lowPrice) {
      UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:notice delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
    }else{
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
        SureIndentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SureIndent"];
        page.productDic = [_productDic mutableCopy];
        page.countSize = _houseSizeLabel.text;
        page.dateTime = _dateTimeLabel.text;
        page.phoneNumber = _phoneLabel.text;
        [[Common getNavigation]pushViewController:page];
    }
    
}


#pragma mark == 图文详情
- (IBAction)detailHandel:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    HouseCleanDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"HouseCleanDetail"];
    page.serviceId = _goodsId;
    page.dateTime = _dateTimeLabel.text;
    page.productDic = _productDic;
    page.houseSize = _houseSizeLabel.text;
    [[Common getNavigation]pushViewController:page];
}

#pragma mark == 更多评价
- (IBAction)moreComments:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    GoodsCommentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"GoodsComment"];
    page.goodsId = _goodsId;
    [[Common getNavigation]pushViewController:page];
}

#pragma mark ==== textFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == _houseSizeLabel) {
        NSString * str = [_houseSizeLabel.text stringByReplacingCharactersInRange:range withString:string];
        _totalSize.text = [NSString stringWithFormat:@"共%@%@",str,_specify];
        
    }
    return YES;
}

#pragma mark ==== UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        
    }else{
        UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"IndentsStoryboard" bundle:nil];
        SureIndentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SureIndent"];
        page.productDic = [_productDic mutableCopy];
        page.countSize = _houseSizeLabel.text;
        page.dateTime = _dateTimeLabel.text;
        page.phoneNumber = _phoneLabel.text;
        page.totalPrice = [_productDic[@"mgooSalePrice"]floatValue];
        [[Common getNavigation]pushViewController:page];

    }
}


#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPagesatView:(BestScrollView *)bsView
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index atView:(BestScrollView *)bsView
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 170), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_imageArray[index][@"titleimg"]]] placeholderImage:[UIImage imageNamed:@"integral2"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
}


#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows = _commitArray.count;
    if (rows>2) {
        rows = 2;
    }
    return rows;
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height= [_heightArray[indexPath.row] floatValue]*VerticalRatio();
    return height ;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodsComentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if (cell == nil) {
        cell= [[GoodsComentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    cell.headImage.frame = flexibleFrame(CGRectMake(10, 11, 26, 26), NO);
    cell.headImage.layer.masksToBounds = YES;
    cell.headImage.layer.cornerRadius = 13*VerticalRatio();
    NSDictionary * dic = _commitArray[indexPath.row];
    NSString * image = dic[@"memeberIcon"];
    if (image) {
        [cell.headImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }else{
        cell.headImage.image = [UIImage imageNamed:@"comment1"];
    }
    
    
    cell.commentInfo.frame = flexibleFrame(CGRectMake(47, 40, 265, 15), YES);
    cell.commentInfo.numberOfLines = 0;
    cell.commentInfo.text = [NSString stringWithFormat:@"%@",dic[@"mgcoContent"]];
    [cell.commentInfo sizeToFit];
    
    cell.name.frame = flexibleFrame(CGRectMake(47, 17, 118, 15), NO);
    cell.name.text = [NSString stringWithFormat:@"%@",dic[@"memberName"]];
    
    cell.date.frame = flexibleFrame(CGRectMake(168, 16, 144, 15), NO);
    NSString * date = [NSString stringWithFormat:@"%@",dic[@"mgcoDate"]];
    if (date && date.length>=19) {
        cell.date.text = [date substringToIndex:19];
    }
    
    NSString * images = [NSString stringWithFormat:@"%@",dic[@"mgcoImage"]];
    NSArray * imagesArray = [images componentsSeparatedByString:@","];
    
    CGFloat height= [_heightArray[indexPath.row] floatValue];
    for (int i = 0; i<imagesArray.count; i++) {
        UIImageView * image = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(50+i*58, height-60, 50, 50), NO)];
        [image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,imagesArray[i]]]];
        [cell addSubview:image];
    }
    
    cell.line.frame = flexibleFrame(CGRectMake(0, height-1, 320, 1), NO);

    
    return cell;
    
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    if (tag==HK_HK_queryMallGoods) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSDictionary * dic= database[@"result"];
            _productDic = dic;
            _imageArray = dic[@"listGoodsImage"];
            if (_imageArray.count==0) {
                [_imageArray addObject:@{@"titleimg":@"integral2"}];
            }
            self.headerScroll.delegate=self;
            self.headerScroll.datasource=self;
            [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];
            
            NSInteger  collect = [[NSString stringWithFormat:@"%@",dic[@"isCollectGoods"]] integerValue];
            if (collect>=1) {
                _collectButton.selected = YES;
            }
            
            _specify = [NSString stringWithFormat:@"%@",dic[@"mgooSpecify"]];
            _totalSize.text = [NSString stringWithFormat:@"共0%@",_specify];
            _specifyLabel.text = [NSString stringWithFormat:@"%@",dic[@"mgooSpecifyLabel"]];
            
            _goodsName.text = [NSString stringWithFormat:@"%@",dic[@"mgooName"]];
            NSString * price = [NSString stringWithFormat:@"￥%@/m²",dic[@"mgooPrice"]];
            NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString: [NSString stringWithFormat:@"%@   %@元起     %@人购买",price,dic[@"mgooSalePrice"],dic[@"mgooSaleNum"]]];
            [str addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:1.000 green:0.976 blue:0.702 alpha:1.000] range:NSMakeRange(price.length, str.length-price.length)];
            [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13*VerticalTexeRatio()] range:NSMakeRange(price.length, str.length-price.length)];
            _goodsDetail.attributedText = str;
            _phoneLabel.text = [NSString stringWithFormat:@"%@",dic[@"mgooPhone"]];
            
        }
    }else if (tag == HK_HK_collectGoods){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
        [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            _collectButton.selected = YES ;
        }
    }else if (tag == HK_HK_deleteCollectGoods){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            _collectButton.selected = NO ;
        }
    }else if (tag==HK_HK_queryAppMallGoodsComment) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _commitArray = database[@"result"][@"rows"];
            
            for (int i = 0; i<_commitArray.count; i++) {
                NSString * commentImage = _commitArray[i][@"mgcoImage"];
                NSString * comment = _commitArray[i][@"mgcoContent"];
                NSInteger height = 0;
                if (commentImage.length==0 ) {
                    height = 68;
                }else{
                    height = 118;
                }
                
                
                int lines = 0;
                CGSize cSize = [comment sizeWithFont:[UIFont systemFontOfSize:14*VerticalTexeRatio()]];
                lines = cSize.width/300*VerticalRatio() + 1 ;
                
                height  += lines * 17;
                
                [_heightArray addObject:@(height)];
            }
            
            NSInteger height = 0;
            if (_heightArray.count==0) {
                _moreButton.hidden = YES;
            }else{
                NSInteger rows = _heightArray.count;
                if (_heightArray.count>2) {
                    rows = 2;
                }
                for (int i = 0; i<rows; i++) {
                    height += [_heightArray[i] integerValue];
                }
            }
            
            _tableView.frame = flexibleFrame(CGRectMake(0, 476, 320, height), NO);
            _moreButton.frame = flexibleFrame(CGRectMake(11, CGRectGetMaxY(_tableView.frame)/VerticalRatio()+5, 297, 33), NO);
            _scroView.contentSize = flexibleSize(CGSizeMake(0, CGRectGetMaxY(_moreButton.frame)/VerticalRatio()+5), NO);
            
            [_commentCount setTitle:[NSString stringWithFormat:@"累计评价(%d)",_commitArray.count] forState:UIControlStateNormal];
            _tableView.delegate = self;
            _tableView.dataSource = self;
            [_tableView reloadData];
            
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
     [self dismissWaitDialog];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
